package com.study.bniarysearch;

public class Test {

    public static void main(String[] args) {
        //求一个数的平方根,精确到小数点6位
//        int i = 38;
//
//
//        System.out.println(i + "的平方根是:" + squareRoot(i));
//        System.out.println(i + "的平方根是:" + squareRoot1(i));


        for (int j = 1; j < 50; j++) {
            double s1 = squareRoot(j);
            double s2 = squareRoot1(j);
            System.out.println(j);
            if (s1 != s2) {
                System.out.println(j + "的平方根: " + s1 + " : " + s2);
            }
        }

    }

    /**
     * 循环求给定值得平方根
     */
    private static double squareRoot(int i) {
        double a = i * 10000000_0000000f;
        double r = 1;
        while (r * r < a) {
            r++;
        }
        //四舍五入
//        System.out.println(r);
        int i1 = (int) (r - 1 + 5) / 10;
//        System.out.println(i1);
        return ((double) i1) / 1000000;
    }

    /**
     * 二分查找 求给定值的平方根
     */
    private static double squareRoot1(int i) {
        double a = i * 10000000_0000000f;
        double low = 0;
        double high = a;
        double mid = 0;
        double res;
        while (Math.abs(a - (res = mid * mid)) > 1) {
            if (res > a) {
                high = mid;
            } else if (res < a) {
                low = mid;
            } else {
                break;
            }
            mid = (low + high) / 2;
        }

//        System.out.println(mid);
        int i1 = (int) (mid - 1 + 5) / 10;
//        System.out.println(i1);
        mid = ((double) i1) / 1000000;
        return mid;
    }

}
